<script setup lang="ts">
import type { CustomerObj, ContactDtl } from './types';

const directStore = useDirectStore();

const searchValue = ref('');
const list = ref<CustomerObj[]>([]);
const customerLoading = ref(false);
const loading = ref(false);

/**
 * 获取客户列表数据
 */
const fetchCustomerData = async () => {
  customerLoading.value = true;
  const params = {
    search: searchValue.value,
  };

  const response = await DirectService.queryCustomerList(params);
  // 初始化时给每个客户添加 contactDtlList 属性，确保响应式
  list.value = (response || []).map((item: CustomerObj) => ({
    ...item,
    contactDtlList: item.contactDtlList || undefined,
  }));
  customerLoading.value = false;
};

/**
 * 打开折叠面板时加载分支机构列表
 */
const handleCollapseOpen = async (item: CustomerObj) => {
  const index = list.value.findIndex(c => c.customId === item.customId);
  if (index === -1) return;

  // 如果已经加载过，则不重复请求
  if (item.contactDtlList && item.contactDtlList.length > 0) {
    return;
  }

  loading.value = true;
  // 请求分支机构列表
  const params = {
    customId: item.customId,
    entryId: item.entryId,
  };
  const response = await DirectService.queryContractDtlList(params);

  list.value[index] = {
    ...list.value[index],
    contactDtlList: response || [],
  };
  loading.value = false;
};

/**
 * 选择分支机构
 */
const handleCollapseSelect = (item: CustomerObj, contactItem: ContactDtl) => {
  directStore.setCustomerObj(item);
  if (contactItem.contactId === -1) {
    directStore.setContactObj({} as ContactDtl);
  } else {
    directStore.setContactObj(contactItem);
  }
  router.push(RouteMap.directAcceptance);
};

onMounted(() => {
  fetchCustomerData();
});
</script>

<template>
  <view class="bg-white h-screen">
    <app-search v-model="searchValue" @search="fetchCustomerData" />
    <scroll-view class="pb-100" scroll-y>
      <app-collapse
        :list="list"
        id-key="customId"
        children-key="contactDtlList"
        @open="handleCollapseOpen"
        @select="handleCollapseSelect"
      >
        <template #title="{ item }">
          <view class="color-black-2">{{ item.customId }}/{{ item.customName }}</view>
          <view v-show="item.entryId" class="color-gray-4 text-12 mt-2">
            {{ item.entryId }}/{{ item.entryName }}
          </view>
        </template>
        <template #content="{ item, children }">
          <view
            v-for="(contactItem, contactIndex) in children"
            :key="contactItem.contactId + contactIndex"
            class="flex items-center justify-between p-4 bg-white border-b border-solid border-t-0 border-r-0 border-l-0 border-gray-100"
            @click="handleCollapseSelect(item, contactItem)"
          >
            <view class="flex-1 text-14">
              {{
                contactItem.contactId === -1
                  ? '客户本级'
                  : `${contactItem.contactId}/${contactItem.contactName}`
              }}
            </view>
            <up-icon class="ml-2" name="arrow-right" size="14"></up-icon>
          </view>
          <view
            v-if="children.length === 0 && !loading"
            class="text-center py-4 color-gray-4 text-12"
          >
            该客户暂无分支机构
          </view>
        </template>
      </app-collapse>
      <app-empty v-if="list.length === 0 && !customerLoading" description="暂无客户" />
    </scroll-view>
  </view>
</template>
